package net.atomarrow.render;

import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.nio.charset.StandardCharsets;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;

import net.atomarrow.ioc.ActionContext;

public class FileRender extends Render {
    public static final String FILE_NAME = "FILE_NAME";
    public static final String FILE_DATA_INPUTSTREAM = "FILE_DATA_INPUTSTREAM";

    @Override
    public void render() {
        HttpServletResponse response = ActionContext.getContext().getResponse();
        String fileName = getAttr(FILE_NAME);
        response.reset();
        response.setContentType("APPLICATION/OCTET-STREAM");
        ServletOutputStream out = null;
        InputStream inStream =null;
        try {
            fileName = response.encodeURL(new String(fileName.getBytes(),
                    StandardCharsets.UTF_8));

            response.setHeader("Content-Disposition", "attachment; filename=\""
                    + fileName + "\"");
            out = response.getOutputStream();
            inStream = getAttr(FILE_DATA_INPUTSTREAM);
            byte[] b = new byte[4 * 1024];
            int len;
            while ((len = inStream.read(b)) > 0){
                out.write(b, 0, len);
            }
            response.setStatus(HttpServletResponse.SC_OK);
            response.flushBuffer();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }finally{
            if(inStream!=null){
                try {
                    inStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(out!=null){
                try {
                    out.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

}
